package com.qf.web;

import com.qf.pojo.Cart;
import com.qf.pojo.CartItem;
import com.qf.pojo.Product;
import com.qf.pojo.User;
import com.qf.service.ProductService;
import com.qf.service.serviceimpl.ProductServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/cart")
public class CartServlet extends BaseServlet {
    //获取购物车功能
    public Cart getCart(HttpServletRequest request,HttpServletResponse response){
        Cart cart = (Cart) request.getSession().getAttribute("cart");//从session中获取购物车
        if(cart==null){//判断是否为空
            cart = new Cart();
            request.getSession().setAttribute("cart",cart);
            return cart;
        }else {
            return cart;
        }
    }

    /**
     * 将购物车项添加购物车功能
     * @param request
     * @param response
     */
    public void addToCart(HttpServletRequest request,HttpServletResponse response)
            throws ServletException, IOException {
        User user = (User) request.getSession().getAttribute("user");
        if(user==null){//判断用户是否登录
            request.getRequestDispatcher("/jsp/login.jsp").forward(request,response);
            return;
        }
        //获取前台传来的参数
        String pid = request.getParameter("pid");
        String cont = request.getParameter("count");
        int count = Integer.parseInt(cont);
        ProductService ps = new ProductServiceImpl();
        Product product = ps.findProductByPid(pid);
        //System.out.println(product);
        CartItem cartItem = new CartItem(product,count);
        Cart cart = getCart(request, response);
        //System.out.println(cart);
        cart.addCart(cartItem);
        response.sendRedirect(request.getContextPath()+"/jsp/cart.jsp");
    }
    /**
     * 删除购物车项
     */
    public void deleteCartItem(HttpServletRequest request,HttpServletResponse response) throws IOException {
        //接收参数
        String pid = request.getParameter("pid");
        Cart cart = (Cart) request.getSession().getAttribute("cart");
        cart.deleteCart(pid);
        response.sendRedirect(request.getContextPath()+"/jsp/cart.jsp");
    }
    /**
     * 清空购物车
     */
    public void clearCart(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        Cart cart = (Cart) request.getSession().getAttribute("cart");
        cart.clearCart();
        request.getSession().removeAttribute("cart");
        /*request.getRequestDispatcher("/jsp/cart,jsp").forward(request,response);*/
        response.sendRedirect(request.getContextPath()+"/jsp/cart.jsp");
    }
}
